package com.adrian.controller;

import com.adrian.api.ApiClient;
import com.adrian.pojo.Product;
import com.adrian.pojo.Type;
import com.adrian.result.MessageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Auther: Adrian
 * @Date: 2020/3/20 20:50
 * @Description:
 */
@Controller
@Scope("prototype")
public class ProductController {

    @Autowired
    private ApiClient apiClient;

    /**
     * 01-查询列表
     *
     * @param model
     * @return
     */
    @RequestMapping("/product_list")
    public String productList(Model model) {
        List<Product> products = apiClient.getList();
        System.out.println("查询到的商品列表:" + products);
        model.addAttribute("products", products);
        //商品模板页面
        return "products";
    }

    @ResponseBody
    @RequestMapping("/product_add")
    public MessageResult addProduct(Product product){
        MessageResult result=null;
        int count = apiClient.addProduct(product);
        if(count>0){
            result = new MessageResult(200, "新增成功");
        }else{
            result = new MessageResult(500, "新增失败");
        }
        return result;
    }


    /**
     * Ajax异步加载下拉框
     * @return
     */
    @ResponseBody
    @RequestMapping("/product_types")
    public List<Type> getTypes() {
        return apiClient.getTypes();
    }
    /**
     * 异步删除
     *
     * @param id
     * @return
     */
    @RequestMapping("/product_delete")
    @ResponseBody
    public MessageResult deleteProduct(int id) {
        MessageResult result;
        int count = apiClient.deleteProduct(id);
        if (count > 0) {
            result = new MessageResult(200, "成功");
        } else {
            result = new MessageResult(500, "失败");
        }
        return result;
    }
    /**
     * 04-更新
     * @return
     */
    @ResponseBody
    @RequestMapping("/product_update")
    public MessageResult product_update(Product product){
        MessageResult result=null;
        int count = apiClient.updateProduct(product);
        if(count>0){
            result = new MessageResult(200, "更新成功");
        }else{
            result = new MessageResult(500, "更新失败");
        }
        return result;
    }
    /**
     * 根据ID查询对象
     * @param id
     * @return
     */
    @RequestMapping("/product_toupdate")
    public String getById(int id,Model model){
        Product product = apiClient.getById(id);
        model.addAttribute("product",product);
        //更新的模板页面上
        return "editproducts";
    }
}
